package com.shuguoyiyou.wechatofficialaccount.controller;

import com.alibaba.fastjson.JSON;
import com.shuguoyiyou.wechatofficialaccount.util.QrCodeUtil;
import io.swagger.annotations.ApiOperation;
import org.json.simple.JSONObject;
import org.json.simple.parser.JSONParser;
import org.json.simple.parser.ParseException;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;

import java.net.URL;
import java.util.Scanner;
import java.util.UUID;

@RequestMapping("/home")
@Controller
public class HomeController {

    //生成带logo的二维码到response
    @RequestMapping("/qrcode")
    public void qrcode(HttpServletRequest request, HttpServletResponse response) {
//        String requestUrl = "http://www.coolbreeze.top:80/weixin/getWeiXinUserInfo/79";
        String requestUrl = "http://wai.free.idcfengye.com:80/weixin/getWeiXinUserInfo/79";
        try {
            OutputStream os = response.getOutputStream();
            QrCodeUtil.encode(requestUrl, "/data/springboot2/logo.jpg", os);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    //生成不带logo的二维码到response
    @RequestMapping("/qrnologo")
    public void qrnologo(HttpServletRequest request, HttpServletResponse response) {
        String requestUrl = "http://www.baidu.com";
        try {
            OutputStream os = response.getOutputStream();
            QrCodeUtil.encode(requestUrl, null, os);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    //把二维码保存成文件
    @RequestMapping("/qrsave")
    @ResponseBody
    public String qrsave() {
        String requestUrl = "http://www.baidu.com";
        try {
            QrCodeUtil.save(requestUrl, "/data/springboot2/logo.jpg", "/data/springboot2/qrcode2.jpg");
        } catch (Exception e) {
            e.printStackTrace();
        }
        return "文件已保存";
    }

    //解析二维码中的文字
    @RequestMapping("/qrtext")
    @ResponseBody
    public String qrtext() {
        //String requestUrl = "http://www.baidu.com";
        String url = "";
        try {
            url = QrCodeUtil.decode("/data/springboot2/qrcode2.jpg");
        } catch (Exception e) {
            e.printStackTrace();
        }
        return "解析到的url:" + url;
    }

    @ApiOperation(value = "文档保存")
    @RequestMapping(value = "/docx/save",
            method = RequestMethod.POST,
            produces = "application/json;charset=UTF-8")
    @ResponseBody
    public void saveWord(@RequestParam("fileName") String fileName, HttpServletRequest request, HttpServletResponse response) {
        PrintWriter writer = null;
        org.json.simple.JSONObject jsonObj = null;
        System.out.println("===saveeditedfile------------");
        try {
            writer = response.getWriter();
            Scanner scanner = new Scanner(request.getInputStream()).useDelimiter("\\A");
            String body = scanner.hasNext() ? scanner.next() : "";
            jsonObj = (JSONObject) new JSONParser().parse(body);
            System.out.println("===saveeditedfile:" + jsonObj.get("status"));
	            /*
	                0 - no document with the key identifier could be found,
	                1 - document is being edited,
	                2 - document is ready for saving,
	                3 - document saving error has occurred,
	                4 - document is closed with no changes,
	                6 - document is being edited, but the current document state is saved,
	                7 - error has occurred while force saving the document.
	             * */
            if ((long) jsonObj.get("status") == 2) {
                /*
                 * 当我们关闭编辑窗口后，十秒钟左右onlyoffice会将它存储的我们的编辑后的文件，，此时status = 2，通过request发给我们，我们需要做的就是接收到文件然后回写该文件。
                 * */
                /*
                 * 定义要与文档存储服务保存的编辑文档的链接。当状态值仅等于2或3时，存在链路。
                 * */
                String downloadUri = (String) jsonObj.get("url");
                System.out.println("====文档编辑完成，现在开始保存编辑后的文档，其下载地址为:" + downloadUri);
                //解析得出文件名
                //String fileName = downloadUri.substring(downloadUri.lastIndexOf('/')+1);
//                String fileName = request.getParameter("fileName");
//                System.out.println("====下载的文件名:" + fileName);

                URL url = new URL(downloadUri);
                java.net.HttpURLConnection connection = (java.net.HttpURLConnection) url.openConnection();
                InputStream stream = connection.getInputStream();
                //更换为实际的路径F:\DataOfHongQuanzheng\java\eclipse-workspace\.metadata\.plugins\org.eclipse.wst.server.core\tmp0\wtpwebapps\Java Example\\app_data\192.168.56.1\
                //File savedFile = new File("F:\\DataOfHongQuanzheng\\onlyoffice_data\\app_data\\"+fileName);


                String path = "F:\\home\\think" + Math.random() * 10 + ".docx";
                System.out.println("path:" + path);
                File savedFile = new File(fileName);

//                String patha=request.getParameter("path");
//                System.out.println("patha:" + patha);
//                String downloadUrl=(String) jsonObj.get("url");
//                System.out.println("downloadUrl:" + downloadUrl);
//                File savedFile = new File( path);

                try (FileOutputStream out = new FileOutputStream(savedFile)) {
                    int read;
                    final byte[] bytes = new byte[1024];
                    while ((read = stream.read(bytes)) != -1) {
                        out.write(bytes, 0, read);
                    }
                    out.flush();
                }
                connection.disconnect();
            }
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (ParseException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        /*
         * status = 1，我们给onlyoffice的服务返回{"error":"0"}的信息，这样onlyoffice会认为回调接口是没问题的，这样就可以在线编辑文档了，否则的话会弹出窗口说明
         * */
        if ((long) jsonObj.get("status") == 6) {
            System.out.println("====保存失败:");
            writer.write("{\"error\":1}");
        } else {
            writer.write("{\"error\":0}");
        }


    }


}
